﻿using Application.Users.Interfaces;
using Application.Users.Models;
using Domain.Entities;
using Domain.ValueObjects;
using MediatR;
using Shared.Crypto;
using Shared.Exceptions;
using System.Collections.Generic;

namespace Application.Users.Commands.CreateUser
{
    public record CreateUserCommand(IList<CreateUserModel> Items) : IRequest<OperationResult<List<Guid>>>;

    public record CreateUserModel
    {
        public string UserName { get; init; } = null!;

        public string PhoneNumber { get; init; } = null!;

        public string Password { get; init; } = null!;
    }

    public class CreateUserCommandHandler(IUserWriteRepository writeRepo, IPasswordHash hash) : IRequestHandler<CreateUserCommand, OperationResult<List<Guid>>>
    {
        public async Task<OperationResult<List<Guid>>> Handle(CreateUserCommand request, CancellationToken ct)
        {
            OperationResult<List<Guid>> result = new()
            {
                Data = []
            };

            foreach (var item in request.Items)
            {
                try
                {
                    User user = User.Create(
                    NickName.Create(item.UserName),
                    PhoneNumber.Create(item.PhoneNumber),
                    hash.Hash(item.Password),
                    null);

                    // 调用写仓储
                    await writeRepo.AddAsync(user, ct);
                    result.Data.Add(user.Id);
                }
                catch(DomainException ex)
                {
                    result.Errors.Add(new ErrorResult
                    {
                        Message = ex.Message
                    });
                }
            }

            return result;
        }

    }
}
